package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import javax.swing.Timer;

import core.UpdateListener;

/**
 * 
 * @author Oscar
 * A controller that handles the updating of the animated images in the
 * center panel.
 */
public class AnimationController extends Observable implements ActionListener {
	private static AnimationController me;
	
	private List<UpdateListener> listeners = new ArrayList<UpdateListener>();
	private List<AnimationInterface> animations = new ArrayList<AnimationInterface>();
	
	private Timer timer;
	
	public static AnimationController getInstance(){
		if(me == null)
			me = new AnimationController();
		return me;
	}
	
	public AnimationController(){
		init();
	}
	
	private void init(){
		timer = new Timer(GUIConstants.frameUpdateTime, this);
		timer.start();
	}
	
	public void addAnimation(AnimationInterface a){
		animations.add(a);
	}
	
	public void addUpdateListener(UpdateListener l){
		listeners.add(l);
	}
	
	private void updateAll(){
		//if(!AnimationUtil.getAnimations().isEmpty())
		for(AnimationInterface a : AnimationUtil.getAnimations())
			a.nextFrame();
		for(UpdateListener l : listeners)
			l.update();
		List<AnimationInterface> animationsToBeRemoved = new ArrayList<AnimationInterface>();
		for(AnimationInterface a : AnimationUtil.getAnimations())
			if(a.wantsToBeRemoved())
				animationsToBeRemoved.add(a);
		for(AnimationInterface a : animationsToBeRemoved)
			AnimationUtil.removeAnimation(a);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		updateAll();
	}
}